# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '23055': {  # witch 支付宝 10-3000
        'API_KEY': 'qgS0InuHKnaxb7t4HrePnpHLJQOYKtYZ',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100005': {
        'API_KEY': 'dbc56f36e20383c2cad6f7eb1909b221',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100018': {  # loki
        'API_KEY': 'dbc56f36e20383c2cad6f7eb1909b221',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100019': {  # zs
        'API_KEY': 'dbc56f36e20383c2cad6f7eb1909b221',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100026': {  # 合乐支付 tt alipayH5 3% 50/100
        'API_KEY': 'e55a28b1bf2a323456ea0b7e759d6108',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100023': {  # 合乐支付 alipayH5 3% 50/100 sp
        'API_KEY': '70314ca6c279ed0aa1d108f91c088ca5',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
    '100027': {  # 合乐支付 dwc
        'API_KEY': '808d45ab3ba50fe7576f6974f18244d3',
        'gateway': 'http://pay.wecard2019.cn/payinfov1.php',
        'query_gateway': 'http://pay.wecard2019.cn/getres.php?mchid={}&out_tradeid={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# paytype+mchid+amount+out_tradeid+time+商户密钥
def generate_sign(d, key):
    s = d['paytype'] + d['mchid'] + d['amount'] + d['out_tradeid'] + d['time'] + key
    _LOGGER.info("weihubaopay sign str: %s", s)
    return _gen_sign(s)


# tradeid+amount+time+pay_result+商户密钥
def generate_notify_sign(d, key):
    s = d['tradeid'] + d['amount'] + d['time'] + d['pay_result'] + key
    _LOGGER.info("weihubaopay notify_sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("weihubaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 微信 WAP:pay.weixin.wap
# 微信原生H5:pay.weixin.h5
# 微信扫码支付:pay.weixin.qrcode
# 微信公众号支付:pay.weixin.js
# 微信 SDK 支付:pay.weixin.sdk
# 支付宝 WAP:pay.alipay.wap
# 支付宝原生H5:pay. alipay.h5
# 支付宝扫码支付:pay.alipay.qrcode
# 支付宝 SDK 支付:pay.alipay.sdk
# QQ扫码支付:pay.qq.qrcode
# QQ WAP:pay.qq.wap
# QQ SDK 支付:pay.qq.sdk
# 银联 SDK 支付:pay.uni.sdk
# 银联扫码支付:pay.uni. qrcode
# 银联 WAP支付:pay.uni.wap
# 银联快捷支付:pay.uni.quickpay
# 银联网关支付:pay.uni.gateway
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'pay.weixin.h5'
    elif service == 'alipay':
        payType = 'pay.alipay.wap'
    elif service == 'alipay_h5':
        payType = 'pay.alipay.h5'
    elif service == 'qq':
        payType = 'pay.qq.wap'
    elif service == 'quick':
        payType = 'pay.uni.quickpay'
    elif service == 'wechat_scan':
        payType = 'pay.weixin.qrcode'
    else:
        payType = 'pay.uni.wap'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('paytype', _get_pay_type(service)),
        ('time', local_now().strftime("%Y%m%d%H%M%S")),
        ('amount', str(int(pay_amount * 100))),
        ('out_tradeid', str(pay.id)),
        ('subject', 'charge'),
        ('clientip', _get_device_ip(info)),
        ('version', '1.0'),
        ('notifyurl', '{}/pay/api/{}/weihubaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("weihubaopay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_tradeid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("weihubaopay create rsp data: %s %s", response.status_code, response.text)
    url = json.loads(response.text)['pay_info'].replace('\/', '/')
    _LOGGER.info('weihubaopay create_url : %s', url)
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("weihubaopay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['out_tradeid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('weihubaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['pay_result'])
    trade_no = data['tradeid']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('weihubaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    url = _get_query_gateway(app_id).format(app_id, pay_order.id)
    _LOGGER.info('weihubaopay query data, %s', url)
    response = requests.get(url, timeout=3)
    _LOGGER.info('weihubaopay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        verify_notify_sign(data, _get_api_key(app_id))
        mch_id = pay_order.mch_id
        trade_status = str(data['pay_result'])
        total_fee = float(data['amount']) / 100.0
        trade_no = data['tradeid']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '0':
            _LOGGER.info('weihubaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
